import config
from flask import Flask, session, g

from exts import db, mail
from models import UserModel

from blueprints.Post import Post
from blueprints.User_Auth import User
from flask_migrate import Migrate


app = Flask(__name__)
app.config.from_object(config)  # 绑定配置文件


db.init_app(app)
mail.init_app(app)

migrate = Migrate(app, db)


app.register_blueprint(Post)    # 生成蓝图
app.register_blueprint(User)


@app.before_request
def my_before_request():
    user_id = session.get('user_id')
    if user_id:
        user = UserModel.query.get(user_id)
        setattr(g, 'user', user)
    else:
        setattr(g, 'user', None)


@app.context_processor
def my_context_processor():
    if hasattr(g, 'user'):
        return {'user': g.user}
    else:
        return {}


if __name__ == '__main__':
    app.run()
